/**
 * 心跳处理
 * Created by macos on 14/11/5.
 */

(function() {

  var protocol = {
    event: '5aa5'
  };
  var redisClient = Redis.client();

  function Heart(server) {

    sails.log.info('onMessage:', protocol);
    server.onMessage(protocol, function(err, msg, res) {

      if (err) {
        sails.log.error(err);
        res.destroy();
        return;
      }

      redisClient.hgetall(res.id, function(err, session){
        sails.log.debug('session after heart:', session);

        if (_.has(session, 'isAuthenticated') && session.isAuthenticated === '1') {

          //清除无用的内存占用
          redisClient.hdel(res.id, 'pubKey');
          redisClient.hdel(res.id, 'secretKey');

          //重新更新会话session失效时间
          redisClient.expire(res.id, session.expire);

          setTimeout(function() {
            res.writeHex('a55a');
          }, 1000);

        } else {
          sails.log.debug('session timeout: ',res.id);
          res.destroy();
        }

      });
    });

  }

  module.exports = {
    runProtocol: function runProtocol(server) {
      return new Heart(server);
    }
  };
})();